package org.lds.logger;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

public final class LoggerFactory {
    private static volatile ILoggerFactory iLoggerFactory;

    private LoggerFactory() {
    }

    public static Logger getLogger(Class c) {
        return getLogger(c.getName());
    }

    public static ILoggerFactory getILoggerFactory() {
        if (iLoggerFactory == null) {
            synchronized (LoggerFactory.class) {
                if (iLoggerFactory == null) {
                    List<ILoggerFactory> loggerFactories = findLoggerFactoryList();
                    if (CollectionUtils.isEmpty(loggerFactories)) {
                        iLoggerFactory = new NOPLoggerFactory();
                    } else {
                        iLoggerFactory = loggerFactories.get(0);
                    }
                }
            }
        }
        return iLoggerFactory;
    }

    public static Logger getLogger(String name) {
        return getILoggerFactory().getLogger(name);
    }

    private static List<ILoggerFactory> findLoggerFactoryList() {
        List<ILoggerFactory> loggerFactories = new ArrayList<>();
        ServiceLoader<ILoggerFactory> serviceLoader = ServiceLoader.load(ILoggerFactory.class);
        for (ILoggerFactory iLoggerFactory : serviceLoader) {
            loggerFactories.add(iLoggerFactory);
        }
        return loggerFactories;
    }
}
